import { useModel } from "umi";
import { useReactive } from "ahooks";

import { FindAllGatewayTypes } from "../../_graphql/organization/gatewayType";
import { AllApplicationsByGatewayType } from "../../_graphql/organization/application";

const useGatewayType = () => {
    const { graphqlFetchPlatform } = useModel("global");

    const state = useReactive({
        dataLoading: false,
        gatewayTypes: [],
        applications: [],
        totalCount: 0,
    });

    const loadGatewayTypes = async () => {
        state.dataLoading = true;
        let res = await graphqlFetchPlatform({
            query: FindAllGatewayTypes,
            variables: {},
        });
        state.gatewayTypes = res?.a?.nodes || [];
        state.dataLoading = false;
    };

    const loadApplications = async ({ pageSize, page, typeName }) => {
        state.dataLoading = true;
        let res = await graphqlFetchPlatform({
            query: AllApplicationsByGatewayType,
            variables: {
                first: pageSize,
                offset: (page - 1) * pageSize || 0,
                contains: typeName,
            },
        });
        state.applications = res?.a?.nodes || [];
        state.totalCount = res?.a?.totalCount || 0;
        state.dataLoading = false;
    };

    return { ...state, loadGatewayTypes, loadApplications };
};

export default useGatewayType;
